package com.ddkj.netty.server.websocket.parkingwebsocket;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.ddkj.netty.Setting;
import com.ddkj.netty.comm.JsonUtil;
import com.ddkj.netty.redis.RedisUtil;
import com.ddkj.netty.server.TCPAddress;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


/**
 * WebSocketHandler
 */
public class WebSocketParkingServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final Log log = LogFactory.getLog(WebSocketParkingServerHandler.class);

    //WEB_SOCKET_PARKING_DDKJ_NETTY会话
    public static final AttributeKey<TCPAddress> WEB_SOCKET_PARKING_KEY = AttributeKey.valueOf(Setting.WEB_SOCKET_PARKING_DDKJ_NETTY);

    //存储channel
    public static Map<String, Channel> channelMap = new HashMap<>();

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 传统的HTTP接入
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }
        // WebSocket接入
        else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        //获取用户数据
        TCPAddress tcpAddress = new TCPAddress(ctx.channel());
        log.info("----(WEB SOCKET 【parking】新用户)--【" + tcpAddress.getClientIP() + "】--上线----");
        ctx.channel().attr(WEB_SOCKET_PARKING_KEY).set(tcpAddress);
        //存储channel
        channelMap.put(tcpAddress.getClientIP(), ctx.channel());
        ctx.writeAndFlush(new TextWebSocketFrame("AA#00#00#" + new Date() + "#"));

    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        //获取用户数据
        TCPAddress tcpAddress = ctx.channel().attr(WEB_SOCKET_PARKING_KEY).get();
        String clientIP = tcpAddress.getClientIP();//ip
        removeIP(clientIP);
        log.info("----WEB SOCKET Parking  用户下线，ip:" + clientIP);
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

        String requestURI = req.uri();

        //客户端ip
        String clientIP = ctx.channel().attr(WEB_SOCKET_PARKING_KEY).get().getClientIP();

        //判断请求域是否正确
        if (!requestURI.contains(Setting.PARKING_URI)) {
            removeIP(ctx.channel().attr(WEB_SOCKET_PARKING_KEY).get().getClientIP());
            return;
        }

        String parkingId = requestURI.substring(Setting.PARKING_URI.length(), requestURI.length());
        log.info("【parkingId】------>" + parkingId + "<------【IP&端口】----->" + clientIP);

        //存储数据,清缓存时所用
        RedisUtil.set(Setting.DDKJ_NETTY_PARKING_WEB_SOCKET_HEADER + parkingId, clientIP);
        RedisUtil.set(clientIP, Setting.DDKJ_NETTY_PARKING_WEB_SOCKET_HEADER + parkingId);

        // 如果HTTP解码失败，返回HHTP异常
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
            return;
        }

        // 构造握手响应返回，本机测试
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://" + Setting.WEB_SOCKET_PARKING_HOST + ":" + Setting.WEB_SOCKET_PARKING_PORT + "/ws", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    /**
     * 处理请求
     */
    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        //返回数据
        String data = null;

        //处理Channel
        Channel receiveChannel = null;

        //获取用户数据
        TCPAddress tcpAddress = ctx.channel().attr(WEB_SOCKET_PARKING_KEY).get();
        String clientIP = tcpAddress.getClientIP();//ip

        // 判断是否是关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        // 判断是否是Ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        String requestMessage = ((TextWebSocketFrame) frame).text();
        try {

            String[] receiveSplit = requestMessage.split(Setting.PARKING_IDENTIFICATION);
            String receive = requestMessage.contains(Setting.PARKING_IDENTIFICATION) ? receiveSplit[0] : null;

            //向接收端发送数据
            if (receive != null) {
                String recip = RedisUtil.get(Setting.DDKJ_NETTY_PARKING_WEB_SOCKET_HEADER + receive);
                receiveChannel = channelMap.get(recip);
                data = receiveSplit[1];
            }

            if (receive == null) {
                String serverParkingreceive = RedisUtil.get(Setting.DDKJ_NETTY_PARKING_WEB_SOCKET_HEADER + Setting.PARKING_SERVER_NAME);
                receiveChannel = channelMap.get(serverParkingreceive);
                data = requestMessage;
            }

            //判断数据是否正确
            String[] split = data.split("#");

            if (split.length == 1) {
                return;
            }

            //心跳应答状态发送
            if (Setting.PARKING_HEARTBEAT_MARK_OK_CODE.equals(split[2])) {
                //ctx.channel().writeAndFlush(new TextWebSocketFrame(String.format(Setting.PARKING_HEARTBEAT_MARK_OK, DateUtil.now())));
                //接收到心跳成功标识后，不错其他处理
                return;
            }

            //返回请求状态
            //ctx.channel().writeAndFlush(new TextWebSocketFrame(data + Setting.PARKING_REQUEST_SUCCESS));

            //向目标发送消息
            receiveChannel.writeAndFlush(new TextWebSocketFrame(data));
            return;

        } catch (Exception e) {
            //参数校验
            data = JSONObject.toJSONString(JsonUtil.getFailJsonObject("系统发生未知的错误！！"));
            ctx.channel().writeAndFlush(new TextWebSocketFrame(data));
        }

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state().equals(IdleState.READER_IDLE)) {
                // ctx.writeAndFlush(new TextWebSocketFrame(String.format(Setting.PARKING_HEARTBEAT_MARK, DateUtil.now())));
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                ctx.writeAndFlush(new TextWebSocketFrame(String.format(Setting.PARKING_HEARTBEAT_MARK, DateUtil.now())));
            } else if (event.state().equals(IdleState.ALL_IDLE)) {

            }

        }

    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {

        // 返回应答给客户端
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        // 如果是非Keep-Alive，关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }

    }


    //清除数据
    protected void removeIP(String ipURI) {

        String whos = RedisUtil.get(ipURI);

        if (whos != null) {
            RedisUtil.remove(whos);
        }
        RedisUtil.remove(ipURI);
        //清空存储Map
        channelMap.remove(ipURI);

    }


}